<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>居中</title>
</head>
<style>
    * {
        margin: 0;
        padding: 0;
    }
    .box1{
        height: 300px;
        background-color: wheat;
        position: relative;
    }
    .box1 div{
        height: 100px;
        width: 80px;
        background-color: darkslategrey;
        position: absolute;
        /* top: 50%;   
        left: 50%; */
        /* margin: -50px -40px;    */
        top: calc(50% - 50px);   /* 和上面注释掉的是一个意思 */
        left: calc(50% - 40px);
    }
    .box2{
        height: 300px;
        position: relative;
        background-color: whitesmoke;
    }
    .box2 div{
        height: 30%;
        width: 20%;
        background-color: darkslategrey;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%,-50%);
    }
    .box3{
        height: 300px;
        background-color: wheat;
    }
    .box3 div{
        height: 30%;
        width: 20%;
        background-color: darkslategrey;
        margin: 50vh auto;
        transform: translateY(-50%);
    }
    .box4{
        height: 300px;
        background-color: whitesmoke;
        display: flex;
    }
    .box4 div{
        height: 30%;
        width: 20%;
        background-color: darkslategrey;
        margin: auto;
    }
</style>

<body>
    <!-- 绝对定位和margin居中 -->
    <div class="box1">
        <div></div>
    </div>
    <!-- 绝对定位和translate居中 -->
    <div class="box2">
        <div></div>
    </div>
    <!-- margin和translate居中 -->
    <div class="box3">
        <div></div>
    </div>
    <!-- flex和margin居中 -->
    <div class="box4">
        <div></div>
    </div>
</body>
</html>